<?php 

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;
use app\admin\model\Basicdata;
use app\admin\model\Member;
use app\admin\model\Povertymember;
use app\admin\model\Image;
use app\admin\model\Area;
use app\admin\model\Villages;

use think\Db;
use think\Exception;
use think\Request;

class Povertyproject extends Base
{

    public function _initialize() {
        parent::_initialize();

        $this->model = 'povertyproject';
        $this->redirect = 'admin/povertyproject/index';

        /*$defaultWhere = $this->getDefaultWhere();
        $defaultWhere['isDelete'] = ['neq', 1];
        $this->defaultWhere = $defaultWhere;*/
        switch ($this->admin->type) {
            case 0:
                $this->defaultWhere = ['a.isDelete' => ['neq', 1]];
                break;
            case 1:
                $this->defaultWhere = ['a.cityId' => $this->admin->cityId, 'a.isDelete' => ['neq', 1]];
                break;
            case 2:
                $this->defaultWhere = ['a.xianId' => $this->admin->xianId, 'a.isDelete' => ['neq', 1]];
                break;
            case 3:
            case 6:
                $this->defaultWhere = ['a.townId' => $this->admin->townId, 'a.isDelete' => ['neq', 1]];
                break;
            case 4:
                $this->defaultWhere = ['a.villageId' => $this->admin->villageId, 'a.isDelete' => ['neq', 1]];
                break;
            default:
                $this->defaultWhere = ['a.isDelete' => ['neq', 1]];
                break;
        }

        $typeList = Basicdata::where(['type' => 'poverty'])->order('sorting')->select();
        $this->assign('typeList', $typeList);
    }

    public function index() {
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }

            $join = [
                ['__MEMBER__ b', 'b.id = a.povertymemberId'],
            ];
            $field = 'a.*, b.name as povertyName';
            $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->order($order)->select();
            $count = $model->alias('a')->where($where)->join($join)->count();

            if ($list) {
                foreach ($list as $item) {
                    // 所在地
                    $item['area'] = getArea($item);

                    $item['typeId'] = Basicdata::where('id', $item['typeId'])->value('name');
                }
            }

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch($this->indexView, [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    public function add(Request $request)
    {
        return parent::add($request);
    }

    public function addPost(Request $request, $redirect = ''){
        $data = $request->param();
        $model = model($this->model);

        $povertymemberId = $data['povertymemberId'];
        $data['id'] = Helper::getUUID();
        $member = Member::where('id', $povertymemberId)->field('cityId,xianId,townId,villageId')->find();
        $data['cityId'] = $member['cityId'];
        $data['xianId'] = $member['xianId'];
        $data['townId'] = $member['townId'];
        $data['villageId'] = $member['villageId'];
        $data['createDate'] = time();
        $data['updateDate'] = time();
        $data['createOper'] = $this->admin->id;
        $data['updateOper'] = $this->admin->id;

        $result = $model->save($data);
        if ($result !== false) {
            // Query执行后的操作
            $model->_after_insert($data);

            // 写入日志
            $logInfo = $this->admin->name . '添加了一条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('添加成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('添加失败');
        }
    }

    public function edit(Request $request){
        $imagesList = Image::where(['relatedId' => $request->param('id'), 'tag' => 'imglist'])->select();
        $this->assign('imgList',$imagesList);
        $this->assign('imgcount',count($imagesList));

        return parent::edit($request);
    }

    public function editPost(Request $request, $redirect = ''){
        $data = $request->param();
        $model = model($this->model);

        $povertymemberId = $data['povertymemberId'];
        $member = Member::where('id', $povertymemberId)->field('cityId,xianId,townId,villageId')->find();
        $data['cityId'] = $member['cityId'];
        $data['xianId'] = $member['xianId'];
        $data['townId'] = $member['townId'];
        $data['villageId'] = $member['villageId'];
        $data['updateDate'] = time();
        $data['updateOper'] = $this->admin->id;

        $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
        if ($result !== false) {
            // Query执行后的操作
            $model->_after_update($data);

            // 写入日志
            $logInfo = $this->admin->name . '更新了一条' . $this->model . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('编辑成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('保存失败');
        }
    }

    public function delete() {
        $model = model($this->model);

        $request = $this->request;
        $id = $request->param('id');

        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        Db::startTrans();
        try{
            $result = $model->where('id', $id)->update(['isDelete' => 1]);
            if($result !== false){
                // 删除项目进展
                $res = db('povertyprojectdetail')->where(['projectId' => $id])->delete();
                if($res === false){
                    Db::rollback();
                    return $this->error('删除项目进展失败！', 'admin/' . strtolower($this->model) . '/index');
                }

                // Query执行后的操作
                $model->_after_delete($id);

                $logInfo = $this->admin->name . '删除了1条' . $this->model . '数据。';
                Common::adminLog($request, $logInfo);

                Db::commit();
                return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
            }else{
                Db::rollback();
                return $this->error('删除失败！', url('admin/' . strtolower($this->model) . '/index'));
            }
        }catch (Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['a.cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['a.xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['a.townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['a.villageId'] = $filter['villageId'];
            }

            if(isset($filter['typeId']) && $filter['typeId']){
                $where['a.typeId'] = $filter['typeId'];
            }
            if(isset($filter['title']) && $filter['title']){
                $where['a.title'] = ['like', '%'.$filter['title'].'%'];
            }
        }

        return $where;
    }
}
